package com.dzt.cloudreader.adapter;

import android.content.Context;
import android.support.v4.view.PagerAdapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ProgressBar;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.drawable.GlideDrawable;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.target.Target;
import com.dzt.cloudreader.R;
import com.dzt.cloudreader.utils.JDensityKit;
import com.dzt.cloudreader.utils.JToastKit;
import com.github.chrisbanes.photoview.PhotoView;

import java.util.ArrayList;

/**
 * ============================================================
 * 项目名称：cloudreader
 * 包名称：com.dzt.cloudreader.adapter
 * 文件名：GalleryPagerAdapter
 * 类描述：
 * 创建时间：2016/3/18 9:16
 * 修改备注：
 * 版本：@version  V1.0
 * ============================================================
 **/
public class GalleryPagerAdapter extends PagerAdapter {
	private ArrayList<String> urls;
	private Context context;
	private LayoutInflater inflater;

	public GalleryPagerAdapter(Context context, ArrayList<String> urls) {
		this.urls = urls;
		this.context = context;
		inflater = LayoutInflater.from(context);
	}

	@Override
	public int getCount() {
		return urls.size();
	}

	@Override
	public boolean isViewFromObject(View view, Object object) {
		return view == object;
	}

	@Override
	public Object instantiateItem(ViewGroup container, int position) {
		View contentView = inflater.inflate(R.layout.item_gallery, container, false);
		final PhotoView imageView = contentView.findViewById(R.id.image);
		final ProgressBar spinner = contentView.findViewById(R.id.loading);
		spinner.setVisibility(View.VISIBLE);
		spinner.setClickable(false);
		Glide.with(context)
				.load(urls.get(position))
				.crossFade(700)
				.listener(new RequestListener<String, GlideDrawable>() {
					@Override
					public boolean onException(Exception e, String model, Target<GlideDrawable> target, boolean isFirstResource) {
						JToastKit.getInstance().showMessage("资源加载异常");
						spinner.setVisibility(View.GONE);
						return false;
					}

					@Override
					public boolean onResourceReady(GlideDrawable resource, String model, Target<GlideDrawable> target, boolean isFromMemoryCache, boolean isFirstResource) {
						spinner.setVisibility(View.GONE);
						/**这里应该是加载成功后图片的高*/
						int height = imageView.getHeight();

						int wHeight = JDensityKit.getInstance().getScreenHeight();
						if (height > wHeight) {
							imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
						} else {
							imageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
						}
						return false;
					}
				})
				.into(imageView);
		container.addView(contentView);
		return contentView;
	}

	@Override
	public void destroyItem(ViewGroup container, int position, Object object) {
		container.removeView((View) object);
	}
}
